package com.demo.web;

import com.demo.domain.Student;
import com.demo.service.StudentService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //1.设置编码
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");

            List<Student> students = new StudentService().GetList();
            //4.创建一个Map对象,给map中设置内容
            Map<String,Object> map = new HashMap<String ,Object>();
            map.put("isLogin",true);
            map.put("data",students);

            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);

            resp.getWriter().println(mapJson);

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
